import * as vscode from 'vscode';
import {isLoginApi, loginApi} from "../api/algAuthorization";

export async function createAuthorizeProvider(context: vscode.ExtensionContext) {

    console.log('恭喜你，你的扩展“alg996authorize”现在是活跃的!');


    let disposable = vscode.commands.registerCommand('extension.authorize', function () {
        const panel = vscode.window.createWebviewPanel(
            'authorize',
            'alg阿灵戈社区授权',
            vscode.ViewColumn.One,
            {
                enableScripts: true
            }
        );
        let accessToken = getAccessToken(context);
        let completion = getCompletion(context);
        let algCopilot = getAlgCopilot(context);
        let email = getEmail(context);
        let password = getPassword(context);
        let rememberMe = getRememberMe(context);
        panel.webview.html = getWebviewContent(
            accessToken,
            completion,
            algCopilot,
            email,
            password,
            rememberMe,
        );

        panel.webview.onDidReceiveMessage(
            message => {
                switch (message.command) {
                    case 'logout':
                        context.globalState.update('authToken', null);
                        vscode.window.showInformationMessage('alg阿灵戈社区：注销成功！');
                        break;
                    case 'login':
                        loginApi(message.email,message.password).then(token => {
                            context.globalState.update('authToken', token);
                            context.globalState.update('rememberMe', message.rememberMe);
                            context.globalState.update('email', message.email);
                            context.globalState.update('completion', message.completion);
                            context.globalState.update('algCopilot', message.algCopilot);
                            if (message.rememberMe){
                                context.globalState.update('password', message.password);
                            }
                            vscode.window.showInformationMessage('alg阿灵戈社区：授权码验证通过，请开始愉快的编码吧！');
                            // 登录成功关闭页面
                            panel.dispose();
                        });
                        return;
                }
            },
            undefined,
            context.subscriptions
        );
    });

    context.subscriptions.push(disposable);
}

function getWebviewContent(
    accessToken: String | undefined,
    completion: String | undefined,
    algCopilot: String | undefined,
    email: String | undefined,
    password: String | undefined,
    rememberMe: String | undefined
) {
    return `

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>alg阿灵戈社区</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #1e1e1e;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: white;
            margin: 0;
        }
        .vscode-form {
            background-color: #252526;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            width: 400px;
        }
        .vscode-title {
            font-size: 24px;
            color: #d4d4d4;
            margin-bottom: 20px;
            text-align: center;
        }
        .vscode-description {
            font-size: 14px;
            color: #d4d4d4;
            margin-bottom: 20px;
            text-align: center;
        }
        .vscode-button {
            background-color: #007acc;
            color: white;
            border: none;
            padding: 10px 20px;
            font-size: 14px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            width: 100%;
        }
        .vscode-button:hover {
            background-color: #005a9e;
        }
        .vscode-button:active {
            background-color: #004377;
        }
        .vscode-input {
            background-color: #1e1e1e;
            color: white;
            border: 1px solid #3c3c3c;
            padding: 10px;
            font-size: 14px;
            border-radius: 5px;
            width: 100%;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            margin-bottom: 20px;
            box-sizing: border-box;
        }
        .vscode-input:focus {
            border-color: #007acc;
            outline: none;
            box-shadow: 0 0 5px rgba(0, 122, 204, 0.5);
        }
        .vscode-label {
            font-size: 14px;
            color: #d4d4d4;
            margin-bottom: 10px;
            display: block;
        }
        .vscode-checkbox {
            margin-bottom: 20px;
        }
        .vscode-logout {
            background-color: transparent;
            color: #d4d4d4;
            border: none;
            padding: 5px 10px;
            font-size: 12px;
            cursor: pointer;
            text-align: center;
            width: 100%;
            margin-top: 10px;
        }
        .vscode-logout:hover {
            color: #ff0000;
        }
    </style>
</head>
<body>
    <form class="vscode-form" id="authForm">
        <div class="vscode-title">alg阿灵戈社区</div>
        <div class="vscode-description">请使用论坛邮箱密码登录</div>
        <label class="vscode-label" for="email">邮箱:</label>
        <input type="email" id="email" class="vscode-input" name="email" placeholder="输入邮箱" value="${email || ''}" required>
        <label class="vscode-label" for="password">密码:</label>
        <input type="password" id="password" class="vscode-input" name="password" placeholder="输入密码" value="${password || ''}" required>
        <label class="vscode-checkbox">
            <input type="checkbox" id="rememberMe" ${rememberMe === 'true' ? 'checked' : ''} /> 记住密码
        </label>
        <label class="vscode-checkbox">
            <input type="checkbox" id="completion" ${completion === 'true' ? 'checked' : ''} /> 启用功能996代码提示
        </label>
        <button type="button" class="vscode-button" onclick="login()">登 录</button>
        <button type="button" class="vscode-logout" onclick="logout()">注销</button>
    </form>
    <script>
        const vscode = acquireVsCodeApi();

        function login() {
            const email = document.getElementById('email')?.value;
            const password = document.getElementById('password')?.value;
            const rememberMe = document.getElementById('rememberMe')?.checked;
            const completion = document.getElementById('completion')?.checked;
            const algCopilot = document.getElementById('algCopilot')?.checked;

            vscode.postMessage({
                command: 'login',
                email: email,
                password: password,
                rememberMe: rememberMe?.toString(),
                completion: completion?.toString(),
                algCopilot: algCopilot?.toString(),
            });
        }

        function logout() {
            localStorage.removeItem('email');
            localStorage.removeItem('password');
            localStorage.removeItem('rememberMe');
            vscode.postMessage({
                command: 'logout'
            });
        }
    </script>
</body>
</html>


    `;
}

/**
 * 授权验证
 */
export function authorizationVerification(context: vscode.ExtensionContext){

    return new Promise((resolve, reject)=>{
        const token = getAccessToken(context);
        if (token) {
            // 使用token进行API请求
            isLoginApi(token).then(bool=>{
                // 如果验证状态，true、false
                if (!bool){
                    // 如果验证不通过，则打开登录页面
                    loginView();
                }
                resolve(bool);
            });
        } else {
            loginView();
            reject(new Error("alg阿灵戈社区：请先登录！"));
        }
    });
}
function loginView(){
    vscode.window.showErrorMessage('alg阿灵戈社区：请先登录插件。[详情](https://alg.zmengine.com/forum.php?mod=viewthread&tid=59&extra=page%3D1)',"登录").then(selection => {
        if (selection === '登录') {
            vscode.commands.executeCommand('extension.authorize');
        }
    });
}
export function getAccessToken(context: vscode.ExtensionContext): string | undefined  {
    return context.globalState.get('authToken');
}

export function getCompletion(context: vscode.ExtensionContext): string | undefined  {
    return context.globalState.get('completion');
}

export function getAlgCopilot(context: vscode.ExtensionContext): string | undefined  {
    return context.globalState.get('algCopilot');
}

export function getEmail(context: vscode.ExtensionContext): string | undefined  {
    return context.globalState.get('email');
}

export function getPassword(context: vscode.ExtensionContext): string | undefined  {
    return context.globalState.get('password');
}
export function getRememberMe(context: vscode.ExtensionContext): string | undefined  {
    return context.globalState.get('rememberMe');
}
